/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.windesheim.archdemo.dao;

import java.util.Date;
import nl.windesheim.archdemo.model.Order;
import nl.windesheim.archdemo.model.OrderLine;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author re0053273
 */
@Transactional
public class OrderDao {
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    
    public List<Order> getAll() {
        return this.sessionFactory.getCurrentSession()
                .createQuery("from my_order order").list();
    }


    /** Recursively saves order and its orderlines, making sure order is set on
     *   each orderline.
     * @param o
     * @return 
    */
    public Order save(Order o){
        Session s = this.sessionFactory.getCurrentSession();
        s.saveOrUpdate(o);
        // Make sure to save orderlines as well
        for(OrderLine ol: o.getOrderLines()){
            ol.setOrder(o);
            s.saveOrUpdate(ol);
        }
        return o;
    }
}